from __future__ import division
from components.recognizer import HandwrittenCharacterRecognizer as HCR
from components.processor import DataProcessor
import config

###################### Config ######################
dataAlreadyExtracted = True
####################################################

def getData(path, dataAlreadyExtracted):
    """Loads feature data or extracts it from image files depending on dataAlreadyExtracted argument."""

    d = DataProcessor(path, config.alphabets, config.dumpFolder, config.extension)
    if dataAlreadyExtracted:
        return d.loadData()
    return d.extractData()

def getAccuracy(trueLabels, predictedLabels):
    """Calculates and returns accuracy."""

    total = len(trueLabels)
    correct = 0
    for i in range(total):
        if trueLabels[i] == predictedLabels[i]:
            correct = correct + 1
    return (correct / total)

def main():
    r = HCR()

    trainingData = getData(config.trainingDataPath, dataAlreadyExtracted)
    classIdx = len(trainingData[0]) - 1
    featureTrain, trueLabelsTrain = r.splitDataIntoFeaturesAndClasses(trainingData, classIdx)
    testingData = getData(config.testingDataPath, dataAlreadyExtracted)
    featuresTest, trueLabelsTest = r.splitDataIntoFeaturesAndClasses(testingData, classIdx)

    numIter = r.train(trainingData, classIdx)
    predictionsOnTrainingData = r.predictUsingDataBatch(featureTrain)
    predictionsOnTestingData = r.predictUsingDataBatch(featuresTest)

    print "Trained in %d iterations." % numIter
    print "Accuracy on training data:", getAccuracy(trueLabelsTrain, predictionsOnTrainingData)
    print "Accuracy on test data:", getAccuracy(trueLabelsTest, predictionsOnTestingData)

if __name__ == '__main__':
    main()